﻿using BacklogParser.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BacklogParser.Parsers
{
    public static class SearchReportParser
    {
        public static List<SearchReport> Parse(XElement elem)
        {
            var result = new List<SearchReport>();

            var reports = elem.Descendants(Constants.Epo + "search-report-information").ToList();

            foreach (var item in reports)
            {
                var parsed = ParseSearchReport(item);
                result.Add(parsed);
            }

            return result;
        }

        private static SearchReport ParseSearchReport(XElement report)
        {
            var result = new SearchReport();

            var attrId = report.Attribute("id");
            if(attrId != null)
            {
                result.Id = attrId.Value;
            }

             
            result.Office = report.Attribute("office").Value;
            result.SearchType = report.Attribute("search-type").Value;
            result.DeclarationOfNoSearch = report.Attribute("declaration-of-no-search").Value;

            var documentIds = report.Descendants(Constants.Epo + "document-id").ToList();

            foreach (var item in documentIds)
            {
                var doc = ParseDocumentId(item);
                result.SearchReportPublication.Add(doc);
            }

            return result;
        }

        public static DocumentId ParseDocumentId(XElement documentId)
        {
            var result = new DocumentId();

            var country = documentId.Descendants(Constants.Epo + "country").FirstOrDefault();
            var kind = documentId.Descendants(Constants.Epo + "kind").FirstOrDefault();
            var date = documentId.Descendants(Constants.Epo + "date").FirstOrDefault();
            var docId = documentId.Descendants(Constants.Epo + "doc-number").FirstOrDefault();
            var langAttr = documentId.Attribute("lang");
            if (langAttr != null)
            {
                result.Lang = langAttr.Value;
            }


            if (country != null)
                result.Country = country.Value;

            if (kind != null)
                result.Kind = kind.Value;

            if (date != null)
                result.Kind = date.Value;

            if (docId != null)
                result.Kind = docId.Value;

            return result;
        }
    }
}
